package com.rpc.spi;

import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.core.io.resource.ResourceUtil;
import com.rpc.serializer.Serializer;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * SPI加载器(支持键值对映射）
 */
@Slf4j
public class SpiLoader {
    /**
     * 存储已加载的类：接口名=>（key=>实现类）
     */
    private static Map<String, Map<String, Class<?>>> loaderMap = new ConcurrentHashMap<>();

    /**
     * 对象实例缓存（避免重复new)
     */
    private static Map<String, Object> instanceCache = new ConcurrentHashMap<>();

    /**
     * 系统SPI目录
     */
    private static final String RPC_SYSTEM_SPI_DIR = "META-INF/rpc/system/";

    /**
     * 用户自定义SPI目录
     */
    private static final String RPC_CUSTOM_SPI_DIR = "META-INF/rpc/custom/";

    /**
     * 扫描的路径
     */
    private static final String[] SCAN_DIRS = new String[]{RPC_SYSTEM_SPI_DIR, RPC_CUSTOM_SPI_DIR};

    /**
     * 动态加载类列表
     */
    private static final List<Class<?>>   LOAD_CLASS_LIST = Arrays.asList(Serializer.class);

    /**
     * 加载所有类型
     */
    public static void loadAll(){
        log.info("加载所有 SPI");
        for(Class<?> clazz : LOAD_CLASS_LIST) {
            load(clazz);
        }
    }

    /**
     * 加载某个类型
     * @param loadClass
     */
    public static void load(Class<?> loadClass) {
        log.info("加载类型为{}的SPI", loadClass.getName());
        //扫描路径，用户自定义的SPI优先级高于系统的SPI
        Map<String, Class<?>> keyClassMap = new HashMap<>();
        for(String scanDir : SCAN_DIRS) {
            List<URL> resources = ResourceUtil.getResources(scanDir + loadClass.getName());
            //读取每个资源文件
            for(URL resouce : resources) {
                try {
                    InputStreamReader isr = new InputStreamReader(resouce.openStream());
                    BufferedReader br = new BufferedReader(isr);
                    String line;
                    while((line = br.readLine())!= null) {
                        String[] strArray = line.split("=");
                        if(strArray.length > 1) {
                            String key = strArray[0];
                            String className = strArray[1];
                            keyClassMap.put(key, Class.forName(className));
                        }
                    }
                } catch (IOException | ClassNotFoundException e) {
//                    e.printStackTrace();
                    log.error("spi resource load error", e);
                }
            }
            loaderMap.put(loadClass.getName(), keyClassMap);
        }
    }

    /**
     * 获取某个接口实例
     * @param clazz
     * @param key
     * @param <T>
     * @return
     */
    public static <T> T getInstance(Class<?> clazz, String key) {
        String className = clazz.getName();
        Map<String, Class<?>> keyClassMap = loaderMap.get(className);
        if(keyClassMap == null){
            throw new RuntimeException(String.format("SpiLoader未加载%s类型", className));
        }
        if(!keyClassMap.containsKey(key)) {
            throw new RuntimeException(String.format("SpiLoader的%s不存在key=%s类型", className, key));
        }

        //获取要加载的实现类型
        Class<?> implClass = keyClassMap.get(key);
        //从实例缓存中加载指定类型的实力
        String implClassName = implClass.getName();
        if(!instanceCache.containsKey(implClassName)) {
            try {
                instanceCache.put(implClassName, implClass.newInstance());
            } catch (InstantiationException | IllegalAccessException  e) {
                String errorMsg = String.format("%s 类型实例失败", implClassName);
                throw new RuntimeException(errorMsg, e);
            }

        }
        return (T)instanceCache.get(implClassName);
    }


}
